package com.xhwl.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.data.dao.*;
import com.xhwl.data.pojo.dto.SceneQueryPageDTO;
import com.xhwl.data.service.ISceneService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SceneServiceImpl extends ServiceImpl<ISceneDao, Scene> implements ISceneService {

    @Autowired
    private ISceneDao sceneDao;
    @Autowired
    private IProjectDao projectDao;
    @Autowired
    private IEnterpriseDao enterpriseDao;
    @Autowired
    private IEnterpriseProjectDao enterpriseProjectDao;

    @Override
    public Page<Scene> page(Scene scene, Page page) {
        return sceneDao.page(page, scene);
    }

    @Override
    public List<Scene> findList(SceneQueryPageDTO sceneQueryPageDTO) {
        if(sceneQueryPageDTO != null && sceneQueryPageDTO.getEnterpriseId() != null) {
            Enterprise enterprise = enterpriseDao.selectById(sceneQueryPageDTO.getEnterpriseId());
            if(enterprise.getType().contains("1")){
                //运营商通过id查
            }else{
                //服务和入驻企业通过项目查
                QueryWrapper<EnterpriseProject> enterpriseProjectQueryWrapper = new QueryWrapper<>();
                enterpriseProjectQueryWrapper.in("enterprise_id", sceneQueryPageDTO.getEnterpriseId());
                List<EnterpriseProject> list = enterpriseProjectDao.selectList(enterpriseProjectQueryWrapper);
                if(CollectionUtils.isNotEmpty(list)){
                    List<Integer> projectIds = list.stream().map(i -> i.getProjectId()).distinct().collect(Collectors.toList());
                    sceneQueryPageDTO.setProjectIds(projectIds);
                }else{
                    //没有授权项目
                    sceneQueryPageDTO.setProjectIds(Arrays.asList(-1));
                }
                sceneQueryPageDTO.setEnterpriseId(null);
            }
        }
        return sceneDao.findList(sceneQueryPageDTO);
    }

    @Override
    public List<Project> projectList(Integer id) {
        QueryWrapper<Project> queryWrapper = new QueryWrapper();
        queryWrapper.eq("scene_id",id);
        queryWrapper.eq("is_deleted",0);
        return projectDao.selectList(queryWrapper);
    }

    @Override
    public Page<Project> projectPage(Scene scene, Page page) {
        QueryWrapper<Project> queryWrapper = new QueryWrapper();
        queryWrapper.eq("scene_id",scene.getId());
        return projectDao.selectPage(page, queryWrapper);
    }
}
